package com.example.administrator.daydayappmarket.list.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.list.activity.ListSecondBodyActivity;
import com.example.administrator.daydayappmarket.list.adapter.ListGameAdapter;
import com.example.administrator.daydayappmarket.list.adapter.ListSolftAdapter;
import com.example.administrator.daydayappmarket.list.model.ListSolftItem;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class ListGameFragment extends Fragment {


    PullToRefreshListView listView;
    ImageView imageView;
    RelativeLayout emptyLayout;

    private RequestQueue requestQueue;
    private List<ListSolftItem> dataSolft;
    private ListSolftAdapter adapter;
    private String path1;

    //head
    @InjectView(R.id.fragment_listsolft_head_Imageview00)
    ImageView fragmentListsolftHeadImageview0;
    @InjectView(R.id.fragment_listsolft_head_Imageview01)
    ImageView fragmentListsolftHeadImageview01;
    @InjectView(R.id.fragment_listsolft_head_textVeiw00)
    TextView fragmentListsolftHeadTextVeiw00;
    @InjectView(R.id.fragment_listsolft_head_textVeiw01)
    TextView fragmentListsolftHeadTextVeiw01;
    @InjectView(R.id.fragment_listsolft_head_Button00)
    TextView fragmentListsolftHeadButton00;
    @InjectView(R.id.fragment_listsolft_head_layout0)
    LinearLayout fragmentListsolftHeadLayout0;
    @InjectView(R.id.fragment_listsolft_head_Imageview10)
    ImageView fragmentListsolftHeadImageview10;
    @InjectView(R.id.fragment_listsolft_head_Imageview11)
    ImageView fragmentListsolftHeadImageview11;
    @InjectView(R.id.fragment_listsolft_head_textVeiw10)
    TextView fragmentListsolftHeadTextVeiw10;
    @InjectView(R.id.fragment_listsolft_head_textVeiw11)
    TextView fragmentListsolftHeadTextVeiw11;
    @InjectView(R.id.fragment_listsolft_head_Button10)
    TextView fragmentListsolftHeadButton10;
    @InjectView(R.id.fragment_listsolft_head_layout1)
    LinearLayout fragmentListsolftHeadLayout1;
    @InjectView(R.id.fragment_listsolft_head_Imageview20)
    ImageView fragmentListsolftHeadImageview20;
    @InjectView(R.id.fragment_listsolft_head_Imageview21)
    ImageView fragmentListsolftHeadImageview21;
    @InjectView(R.id.fragment_listsolft_head_textVeiw20)
    TextView fragmentListsolftHeadTextVeiw20;
    @InjectView(R.id.fragment_listsolft_head_textVeiw21)
    TextView fragmentListsolftHeadTextVeiw21;
    @InjectView(R.id.fragment_listsolft_head_Button20)
    TextView fragmentListsolftHeadButton20;
    @InjectView(R.id.fragment_listsolft_head_layout2)
    LinearLayout fragmentListsolftHeadLayout2;
    @InjectView(R.id.fragment_listsolft_head_Imageview00)
    ImageView fragmentListsolftHeadImageview00;


    private List<ListSolftItem> dataHead;
    private View headView;
    private   String path="http://img.ttigame.com";

    private int index=1;

    public ListGameFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        dataSolft=new ArrayList<>();
        dataHead = new ArrayList<>();
        path1=null;

        headView = LayoutInflater.from(getContext()).inflate(R.layout.list_solft_headview,null);
        adapter = new ListSolftAdapter(getContext(),dataSolft);

        requestQueue= Volley.newRequestQueue(getContext());
        solftRequest();

    }

    private void solftRequest() {

        StringRequest stringRequest=new StringRequest(Request.Method.GET, Contacts.LIST_GAME+index, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                path1=response;
                try {
                    JSONArray arr=new JSONArray(path1);
                    for (int i = 3; i < arr.length(); i++) {
                        JSONObject jsonObject = arr.getJSONObject(i);
                        JSONObject data = jsonObject.getJSONObject("data");
                        ListSolftItem listSolftItem=new ListSolftItem();
                        listSolftItem.strJson(data);
                        dataSolft.add(listSolftItem);
                    }

                    if (index==1) {
                        for (int i = 0; i < 3; i++) {
                            JSONObject jsonObject = arr.getJSONObject(i);
                            JSONObject data = jsonObject.getJSONObject("data");
                            ListSolftItem listSolftItem = new ListSolftItem();
                            listSolftItem.strJson(data);
                            dataHead.add(listSolftItem);
                        }
                    }

                    adapter.notifyDataSetChanged();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (dataHead.get(1).getIcon_url().startsWith("h")){
                                Glide.with(getContext()).load(dataHead.get(1).getIcon_url()).into(fragmentListsolftHeadImageview00);
                            }else {
                                Glide.with(getContext()).load(path+dataHead.get(1).getIcon_url()).into(fragmentListsolftHeadImageview00);
                            }
                            fragmentListsolftHeadTextVeiw00.setText(dataHead.get(1).getName());
                            int i = Integer.parseInt(dataHead.get(1).getDownload_count());
                            double v = ((double) (i / 1000)) / 10.0;
                            fragmentListsolftHeadTextVeiw01.setText(v+"万人下载");

                            if (dataHead.get(0).getIcon_url().startsWith("h")){
                                Glide.with(getContext()).load(dataHead.get(0).getIcon_url()).into(fragmentListsolftHeadImageview10);
                            }else {
                                Glide.with(getContext()).load(path+dataHead.get(0).getIcon_url()).into(fragmentListsolftHeadImageview10);
                            }
                            fragmentListsolftHeadTextVeiw10.setText(dataHead.get(0).getName());
                            int i1 = Integer.parseInt(dataHead.get(0).getDownload_count());
                            int i2 = i1 / 10000;
                            fragmentListsolftHeadTextVeiw11.setText(i2+"万人下载");

                            if (dataHead.get(2).getIcon_url().startsWith("h")){
                                Glide.with(getContext()).load(dataHead.get(2).getIcon_url()).into(fragmentListsolftHeadImageview20);
                            }else {
                                Glide.with(getContext()).load(path+dataHead.get(2).getIcon_url()).into(fragmentListsolftHeadImageview20);
                            }
                            fragmentListsolftHeadTextVeiw20.setText(dataHead.get(2).getName());
                            int i3 = Integer.parseInt(dataHead.get(2).getDownload_count());
                            int i4 = i3 / 10000;
                            fragmentListsolftHeadTextVeiw21.setText(i4+"万人下载");

                    headlistnerSolft();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        stringRequest.setTag("g");
        requestQueue.add(stringRequest);
        requestQueue.start();

    }


    public void headlistnerSolft(){

        if (dataHead != null) {
            fragmentListsolftHeadImageview00.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND_GAME+ dataHead.get(1).getId());
                    intent.putExtra("tag",1);
                    startActivity(intent);
                }
            });

            fragmentListsolftHeadImageview10.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND_GAME+ dataHead.get(0).getId());
                    intent.putExtra("tag",1);
                    startActivity(intent);
                }
            });

            fragmentListsolftHeadImageview20.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND_GAME+ dataHead.get(2).getId());
                    intent.putExtra("tag",1);
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_list_game, container, false);

        listView= (PullToRefreshListView) view.findViewById(R.id.fragment_listgame_pullToRefreshListView);
        imageView= (ImageView) view.findViewById(R.id.fragment_listgame_empty_image);
        emptyLayout= (RelativeLayout) view.findViewById(R.id.fragment_listgame_RelativeLayout_empty);

        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(imageView);
        listView.setEmptyView(emptyLayout);
//        adapter = new ListGameAdapter(getContext(),dataSolft);
        listView.setAdapter(adapter);

        listView.getRefreshableView().addHeaderView(headView);

        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (dataSolft!=null) {
                                    dataSolft.clear();
                                }
                                index=1;
                                solftRequest();
                                refreshView.onRefreshComplete();
                            }
                        });
                    }
                },1000);


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                index++;
                solftRequest();
                refreshView.onRefreshComplete();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (dataSolft!=null&&position>1) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND_GAME+ dataSolft.get(position-2).getId());
                    intent.putExtra("tag",1);
                    startActivity(intent);
                }
            }
        });

        ButterKnife.inject(this, view);



        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        requestQueue.cancelAll("g");
    }


}
